<?php

namespace app\index\controller;

use think\cache\driver\Redis;
use think\Controller;
use think\Db;
use think\Session;

class Login extends Controller
{
    public function login()
    {
        return view();
    }

    public function dologin()
    {
        $utel = input('utel');
        $pass = md5(input('upass'));
        $user_info = Db::name('vip')
            ->field(['uid', 'utel', 'username','upass'])
            ->where('utel', $utel)
            ->find();
        $uid = $user_info['uid'];
        if (empty($user_info)) {
            $this->error('该用户不存在', url('index/Login/login'));
        }
//        //检查30min内密码错误次数
        $wrongTimes = $this->checkPassWrongTimes($uid);
//        错误次数过多，超过限制
        if ($wrongTimes == false) {
            $this->error('你刚刚输错密码次数过多，为了保证账户安全，系统已经将您账号锁定30分钟');
        }
//        //判断密码输入是否正确
        if ($pass == $user_info['upass']) {
            //登录成功操作
            Session::set('user_info', $user_info);
            $this->success('登录成功');
        } else {
            //记录密码错误次数
            $this->recordPassWrongTimes($uid);
            $this->error('密码输入错误，请重试');
        }
    }

    protected function checkPassWrongTimes($uid, $min = 30, $wtime = 3)
    {
        $time = time();
        $pretime = $time - $min * 60;
        $wrongTimes = Db::name('user_login_info')
            ->field(true)
            ->where('uid',$uid)
            ->where('UNIX_TIMESTAMP(logintime)','between',$pretime.','.$time)
            ->select();
        if(count($wrongTimes)>=$wtime){
            return false;
        }
        if(count($wrongTimes)==0){
            return true;
        }
        return count($wrongTimes);
    }

    protected function recordPassWrongTimes($uid)
    {
        $recordPassWrong = Db::name('user_login_info')
            ->insert([
                'uid' => $uid,
                'pass_wrong_time_status' => 2
            ]);
    }
}
